<template>
  <VanField
    :model-value="modelValue"
    class="data-field"
    is-link
    readonly
    @click="showPicker = true"
    v-bind="fieldAttrs"
  />
  <VanPopup v-model:show="showPicker" position="bottom">
    <VanDatePicker
      v-if="showPicker"
      :model-value="currentDate"
      :min-date="new Date(2000, 0, 1)"
      :max-date="new Date(2100, 12, 30)"
      @confirm="onConfirm"
      @cancel="showPicker = false"
      v-bind="dateAttrs"
    />
  </VanPopup>
</template>

<script setup>
import { ref, computed, useAttrs } from "vue";
import dayjs from "dayjs";

const props = defineProps({
  format: {
    type: String,
    default: "YYYY-MM-DD",
  },
  modelValue: String,
});

const emits = defineEmits("update:modelValue");

const showPicker = ref(false);
const currentDate = computed(() => {
  return props.modelValue
    ? dayjs(props.modelValue, props.format).format("YYYY-MM-DD").split("-")
    : [];
});

const attrs = useAttrs();
const fieldAttrs = computed(() => {
  let result = {};

  Object.keys(attrs).forEach((key) => {
    if (!/^date|^onDate/.test(key)) {
      result[key] = attrs[key];
    }
  });

  return result;
});
const dateAttrs = computed(() => {
  let result = {};

  Object.keys(attrs).forEach((key) => {
    if (/^date/.test(key)) {
      let newkey = key.replace(/^data-?/, "");
      newkey[0] = newkey[0].toLocaleLowerCase();
      result[newkey] = attrs[key];
    } else if (/^onDate/.test(key)) {
      result[key.replace(/^onDate/, "on")] = attrs[key];
    }
  });

  return result;
});

const onConfirm = ({ selectedValues }) => {
  showPicker.value = false;

  emits(
    "update:modelValue",
    dayjs(selectedValues.join("-")).format(props.format)
  );
};
</script>

<style lang="scss" scoped></style>
